#include"mystdio.h"
#include<string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<stdlib.h>
#include<unistd.h>

const char* ToString(int flag)
{
    if(flag & NONE_FLUSH)
    {
        return "NONE_FLUSH";
    }else if(flag & LINE_FLUSH)
    {
        return "LINE_FLUSH";
    }else if(flag & FULL_FLUSH)
    {
        return "FULL_FLUSH";
    }
    return "UNKNOW";
}

void DebugPrint(myFILE*fp)
{
    printf("outbuffer:%s\n",fp->outbuffer);
    printf("fd:%d\n",fp->fileno);
    printf("pos:%d\n",fp->pos);
    printf("cap:%d\n",fp->cap);
    printf("flysh_mode:%s\n",ToString(fp->flush_mode));
}

//打开接口
myFILE* myfopen(const char* pathname,const char* mods)
{
    int flag=0;
    if(strcmp(mods,"r")==0)
    {
        flag|=O_RDONLY;
    }else if(strcmp(mods,"w")==0)
    {
        flag|=(O_WRONLY|O_CREAT|O_TRUNC);
    }else if(strcmp(mods,"a"))
    {
        flag|=(O_WRONLY|O_CREAT|O_APPEND);
    }else{
        return NULL;
    }
    int fd=0;
    if(flag&O_RDONLY)
    {
        fd=open(pathname,flag);
    }else{
        umask(0);
        fd=open(pathname,flag,0666);
    }
    if(fd<0)
    {
        return NULL;
    }
    myFILE* fp = (myFILE*)malloc(sizeof(myFILE));
    if(fp==NULL)
    {
        return NULL;
    }
    fp->fileno=fd;
    fp->pos=0;
    fp->cap=SIZE;
    fp->flush_mode=LINE_FLUSH;
    return fp;
}
//刷新函数
void my_fflush(myFILE*fp)
{
    if(fp->pos==0)
    {
        return;
    }
    //满足刷新条件，直接调用系统调用接口
    write(fp->fileno,fp->outbuffer,fp->pos);
    fp->pos=0;
}

//写入接口
int my_fwrite(myFILE*fp,const char*s,int size)
{
    //写入
    memcpy(fp->outbuffer+fp->pos,s,size);
    fp->pos+=size;
    //如果是行刷新且最后一个元素为'\n'
    //就刷新到内核缓冲区中
    if((fp->flush_mode & LINE_FLUSH)&&(fp->outbuffer[fp->pos-1]=='\n'))
    {
        my_fflush(fp);
    }else if((fp->flush_mode & FULL_FLUSH)&&(fp->pos==fp->cap))
    {
        my_fflush(fp);
    }
    return size;
}
//关闭接口
void myfclose(myFILE*fp)
{
    //关闭文件之前，就刷新
    my_fflush(fp);
    close(fp->fileno);
    free(fp);
}
